(function (window) {
    let u = {};
    u.url = "http://localhost/sh/public/";
    //u.url = "http://wx.newamstar.com:8078/erp/public/";
    u.addrole = [];
    u.alipay_refill = ()=>{
        $.get(u.url + 'get_goldcz_list',res=>{
            let str="";
            res.forEach(function(e,i,a){
                str+=`<li><input type="radio" name="cztype" value="${e.tccode}">${e.tcname}(${e.price})</li>`;
            })
            layer.open({
                type: 1,
                skin: 'layui-layer-demo', //样式类名
                closeBtn: 1, //不显示关闭按钮
                anim: 2,
                area:["300px","400px"],
                shadeClose: true, //开启遮罩关闭
                content: `
                     <ul style="text-align: center" class="czlist">
                        ${str}
                    </ul>
                    <div style="text-align: center"><button onclick="$api.goldcz();" class="layui-btn layui-btn-warm" id="btn">确认充值</button></div>
                    `
            });
        })
    },

    u.goldcz = ()=>{
        //获取套餐码
        let tccode = $(".czlist input[type='radio']:checked").val(),down_type=1;
        if(!tccode){
            layer.msg('必须选择一个套餐类型');
            return false;
        }
        layer.confirm('是否确认跳转支付宝页面?', {
            btn: ['是', '否'] //按钮
        }, function () {
            window.open(`${u.url}trade_pc_pay?down_type=${down_type}&gid=${tccode}`);
            layer.confirm('是否确认支付完成?', {
                btn: ['是', '否'] //按钮
            }, function () {
                //手动点击确认订单状态
                location.reload();
            }, function () {

            });
        }, function () {

        });
    },

    u.gettree = (param = 1, data) => {
        if (param == 1) {
            $(".easyui-tree").tree({
                url:  u.url+"/gettree",
                method: "GET",
                animate: true,
                checkbox: false,
                onSelect: function (node) {
                    node.state == "closed" ? ($(this).tree('expand', node.target)) : ($(this).tree('collapse', node.target));
                },
                onClick: function (node) {
                    if (!node.children) {
                        u.addTab(node.text, node.href);
                    }
                }
            });
        } else if (param == 2) {
            $(".easyui-tree").tree({
                url:  u.url+"/gettree",
                method: "GET",
                animate: true,
                checkbox: true,
                onCheck: function (node, checked) {
                    u.addrole = [];
                    ($(this).tree('getChildren')).map(item => {
                        if (item.checkState == "indeterminate" || item.checkState == "checked")
                            u.addrole.push(item.id)
                    });
                },
                onSelect: function (node) {
                    node.state == "closed" ? ($(this).tree('expand', node.target)) : ($(this).tree('collapse', node.target));
                }
            });
        } else if (param == 3) {
            //param=3 数据源不从接口获取，直接传入
            $(".easyui-tree").tree({
                data: data,
                animate: true,
                checkbox: true,
                onCheck: function (node, checked) {
                    u.addrole = [];
                    ($(this).tree('getChildren')).map(item => {
                        if (item.checkState == "indeterminate" || item.checkState == "checked")
                            u.addrole.push(item.id)
                    });
                },
                onSelect: function (node) {
                    node.state == "closed" ? ($(this).tree('expand', node.target)) : ($(this).tree('collapse', node.target));
                },
                onLoadSuccess: function (node, data) {
                    u.addrole = [];
                    ($(this).tree('getChildren')).map(item => {
                        if (item.checkState == "indeterminate" || item.checkState == "checked")
                            u.addrole.push(item.id)
                    });
                }
            });
        }
    },
    u.addTab = function (title, url, param = 1) {
            let jq = top.jQuery, newurl = u.url + url;
            if (param == 2) {
                //param为2是需要勾选后再进行跳转;
                let sel = $("#dg").datagrid('getSelected');
                if (!sel) {
                    u.infoDialog("请勾选一条数据后在编辑");
                    return false;
                }
                //console.log(sel);
                let data = $("#dg").datagrid('getSelected');
                newurl = u.url + url + "?id=" + data.id;
            }
            if (param == 3) {
                let data = $("#dg").datagrid('getSelections'),tips = '';
                if(data.length>1){
                    u.infoDialog("最多只能勾选一条(编辑操作)");
                    return false;
                }else if(data.length==0){
                    u.infoDialog("请至少勾选1条");
                    return false;
                }else{
                    // let sel = $("#dg").datagrid('getSelected');
                    // if (!sel) {
                    //     u.infoDialog("请勾选一条数据后在编辑");
                    //     return false;
                    // }
                    let data = $("#dg").datagrid('getSelected');
                    newurl = u.url + url + "?id=" + data.id;
                }
            }
            if (jq('.easyui-tabs').tabs('exists', title)) {
                jq('.easyui-tabs').tabs('select', title);
                let selTab = jq('.easyui-tabs').tabs('getSelected');
                jq('.easyui-tabs').tabs('update', {
                    tab: selTab,
                    options: {
                        content: u.createFrame(newurl)
                    }
                })
            } else {
                let content = `<iframe scrolling="auto" frameborder="0"  src=${newurl} style="width:100%;height:100%;"></iframe>`;
                jq('.easyui-tabs').tabs('add', {
                    title: title,
                    content: content,
                    closable: true
                });
            }
        },
        u.check_has_one = function (dg, param) {
            let ishave = $(dg).datagrid('getSelected');
            if (!ishave) {
                $.messager.alert('消息', '请至少勾选一条');
                return false;
            } else if (!param && ishave.length > param) {
                $.messager.alert('消息', `请至少勾选${param}条`);
            } else {
                return true;
            }
            return this;
        },
        u.initwin = newOptions => {
            let options = {width: 500, height: 300, modal: true, closed: true, maximizable: false,};
            let newoptions = $.extend(false, options, newOptions);
            $('#w').window(newoptions);
        },
        u.createFrame = url => '<iframe scrolling="auto" frameborder="0"  src="' + url + '" style="width:100%;height:100%;"></iframe>',
        u.myDataGird = function () {
            u.initwin();
            for (let i = 0; i < arguments.length; i++) {
                let args = arguments[i];
                if(args){
                    let options = {
                        method: args.method || 'get',
                        nowrap: args.nowrap || true,
                        pagination: true,
                        striped: args.striped || true,
                        pageSize: 50,
                        pageList: [10, 20, 30,40,50], 
                        rownumbers: true,
                        fitcolumns: true,
                        loadFilter: function(data){  
                            // 可以在这里处理数据，比如转换数据格式  
                            // 但由于是假分页，你不需要在这里做分页处理
                            return data;  
                        },  
                       
                        singleSelect: args.singleSelect || true,
                        loadMsg: '正在加载数据，请稍候...',
                        emptyMsg: '<span>没有相关记录</span>',
                        onSelect: args.onSelect,//单击行                 参数:index,row
                        onClickRow: args.onClickRow,//获取选中行的数据     参数:index,row
                        onDblClickRow: args.onDblClickRow,//双击行       参数:index,row
                        onDblClickCell: args.onDblClickCell,//双击单元格 参数:index,field,value
                        fit: false,//args.singleSelect || false,
                        onBeforeCheck: function(index, row) {
                            // if(row.pzbh!=null){   
                            //     var checkBoxes = $('.datagrid-header-check input[type="checkbox"]');  
                            //     checkBoxes.prop('disabled', true);
                            //     return false; // 阻止勾选
                            // }
                        },
                        onBeforeSelect:function(index, row){
                            // if(row.pzbh!=null){
                            //     var checkBoxes = $('.datagrid-header-check input[type="checkbox"]');  
                            //     checkBoxes.prop('disabled', true);  
                            //     return false; // 阻止勾选
                            // }
                        },
                        onBeforeLoad: () => {
                        },
                        onLoadSuccess: res => {
                       
                        }
                    };
                    let newOption = $.extend(false, options, arguments[i]), obj = newOption['obj'],
                        hei = newOption['hei'] || 33;

                    $(function () {
                        //固定高度  $('.panel-htop')是顶部搜索区域的高度
                        //newOption['height'] = $(document.body).height() - $('.panel-htop').height() - hei;//固定高度，左右结构252
                        //alert($('.panel-htop').height())
                        if(args.tt == 1){
                            //如果页面同时有两个表格,为第二个表格指定新的高度
                            newOption['height'] = $(document.body).height() - ($('.panel-htop').height()+$(".layout-panel-center").height()+5);
                        }else if(args.tt==2){
                            newOption['height'] = $(document.body).height() - ($('.panel-htop').height()+230);
                        }else if(args.tt==3){
                            newOption['height'] = $(document.body).height() - ($('.panel-htop').height()+32);
                        }

                        $(obj).datagrid(newOption);
                        $(obj).datagrid('getRows');
                    })
                }
                    /////
                }

        }

    u.gettabs = function () {
        $('.easyui-tabs').tabs({
            onSelect: function (title, index) {
                var select = $('.easyui-tabs').tabs('getTab', index);
                if (title == "公告列表" || title == "首页" || title == "活动列表" || title == "礼品兑换列表") {
                    let url = $(select.panel('options').content).attr('src') || header + "Index/girdindex";
                    $('.easyui-tabs').tabs("update", {
                        tab: select,
                        options: {
                            title: title,
                            content: "<iframe scrolling='auto' frameborder='0'" +
                                "src='" + url + "' style='width:100%;height:100%;'></iframe>"
                        }
                    })
                } else {
                    let url = $(select.panel('options').content).attr('src') || header + "Index/first";
                }
            }
        })
    }

    u.editpwd = function(){
        // let options = {width: 500, height: 300, modal: true, closed: true, maximizable: false,};
        // //let newoptions = $.extend(false, options, newOptions);
        // $('#w').window(options);
        $('#w').window({
            title: '密码修改', width: 500, height: 300, modal: true, onClose: function () {

            }
        });
        $('#w').window('open');
    }

    u.shdelete = function(){
        let data = $("#dg").datagrid('getSelections');
                if (data.length==0) {
                    u.infoDialog("请至少勾选一条数据");
                    return false;
                }
                $.post(u.url + 'shdelete', {"data":data}, res => u.infoDialog(res.msg))

    }

    u.shundo = function(){
        let data = $("#dg").datagrid('getSelections');
                if (data.length==0) {
                    u.infoDialog("请至少勾选一条数据");
                    return false;
                }
                $.post(u.url + 'shundo', {"data":data}, res => u.infoDialog(res.msg))

    }

    u.saveeditpwd = function(){
        //let pwd1=$(".ysmm").textbox('getValue');
        let tips = '更新信息成功';
        let formdata = $("#form2").serializeObject();
        if(formdata.ysmm!=formdata.xmm){
            $.messager.alert("消息","两次密码输入不一致,请重新输入!");
            return false;
        }else{
            //console.log(formdata);
            u.confirm('确认修改密码吗?', () => $.get(u.url + "update_user_password", formdata, res => u.tool1(tips)));
        }


    }
    

    u.createDate = function (){
        let date = new Date();  
        let year = date.getFullYear();  
        let month = String(date.getMonth() + 1).padStart(2, '0'); // 使用padStart函数在前面补0  
        let day = String(date.getDate()).padStart(2, '0'); // 同上
        return year + '-' + month + '-' + day;
    }
    u.doSearch = function () {
        $("#dg").datagrid('load', $('#form').serializeObject());
        return this;
    }
    u.clearFrom = () => $("#form").form("clear");
    u.update_role = () => $.get(u.url + 'updaterole', $('#form').serializeObject(), res => u.infoDialog("保存成功"));
    u.add_role = () => {
        let json = $('#form').serializeObject();
        json['auth'] = u.addrole;
        $.get(u.url + 'addrole', json, res => u.infoDialog("保存成功"))
    };
    //新增管理员
    u.addmanager = () => $.get(u.url + 'addmanager', $('#form').serializeObject(), res => u.infoDialog("保存成功"));
    //删除管理员
    u.deleteManager = function () {
        if (u.is_select_one("请勾选数据后再操作")) {
            let data = $("#dg").datagrid('getSelected');
            u.confirm('是否确认删除?', () => $.get(u.url + "deletemanager", {"mg_id": data.mg_id}, res => u.tool1('删除成功')))
        }
    }
    //编辑更新客户信息--部分主要字段
    u.updateCustomInfo = function(){
        let data = $('#form').serializeObject();
        //console.log(data);
        u.confirm('是否确认更新客户信息?', () => $.get(u.url + "updateCustomInfo", data, res => u.tool1('更新成功')))
    }

    //新增商品
    u.addgood = function () {
        //let c = ue.getContent();
        let obj = $("#form").serializeObject();//editorValue editor的内容
        obj['imgurl'] = picsarr.toString();//细节多图
        obj['singleimg'] = picsarr2;//列表单图
        //obj['modelfiles']  = modefiles;//模型zip文件
        obj['X-CSRF-TOKEN'] = '{{ csrf_token() }}';
        if (!obj.goodname) {
            u.infoDialog("模型名称不能为空");
            return false;
        }
        if (!obj.imgurl) {
            u.infoDialog("商品细节图片还未上传");
            return false;
        }
        //if(!obj.modelfiles) {u.infoDialog("模型文件还未上传"); return false;}
        if (!obj.dg) {
            u.infoDialog("灯光不能为空");
            return false;
        }
        if (!obj.cztt) {
            u.infoDialog("材质贴图不能为空");
            return false;
        }
        if (!obj.fg) {
            u.infoDialog("风格不能为空");
            return false;
        }
        if (!obj.ms) {
            u.infoDialog("面数不能为空");
            return false;
        }
        if (!obj.price) {
            u.infoDialog("兑换价格不能为空");
            return false;
        }
        if (!obj.score) {
            u.infoDialog("兑换积分不能为空");
            return false;
        }
        if (!obj.singleimg) {
            u.infoDialog("图片列表图片还未上传");
            return false;
        }
        if (!obj.ssdl) {
            u.infoDialog("所属大类不能为空");
            return false;
        }
        if (!obj.sszl) {
            u.infoDialog("所属子类不能为空");
            return false;
        }
        //console.log(obj);
        $.post(u.url + 'addgood', obj, res => u.infoDialog("保存成功"))
    }
    //商品上架、下架
    u.good_sj_xj = function (param) {
        if (u.is_select_one("请勾选数据后再操作")) {
            let data = $("#dg").datagrid('getSelected'), tips = param == 1 ? '是否确认上架商品' : '是否确认下架商品';
            u.confirm(tips, () => $.get(u.url + "goodsjxj", {"id": data.id, 'param': param}, res => u.tool1('上架成功')))
        }
    }
    //新增/更新门店
    u.addshop = function (param) {
        if (param == 1) {
            //新增门店
            $('#w2').window({
                title: '新增客户信息', width: 800, height: 400, modal: true, left: 150,
                top:50,onClose: function () {
                    u.reloadTable();
                    $("#form2").form("clear");
                }
            });
            $('#w2').window('open');
        } else if (param == 2) {
            //编辑门店
            if (u.is_select_one("请勾选数据后再操作")) {
                let data = $("#dg").datagrid('getSelected');
                $.get(u.url + 'detailgood', {id: data.id}, res => {
                    //console.log(res.data);
                    $('.khqm').textbox('setValue', res.data.khqm);
                    $('.khjc').textbox('setValue', res.data.khjc);
                    //$('.gjnr').textbox('setValue', res.data.gjnr);
                }, 'json')

                $('#w1').window({
                    title: '编辑客户信息', width: 900, height: 500, modal: true, onClose: function () {
                        u.reloadTable();
                        $("#form2").form("clear");
                    }
                });
                $('#w1').window('open');
            }
        }
    }
    //删除客户
    u.delshop = function () {
        if (u.is_select_one("请勾选数据后再操作")) {
            // let data = $("#dg").datagrid('getSelections');
            // let ids = [];
            // for(let i = 0;i<data.length;i++){
            //     ids.push(data[i]['id']);
            // }
            let ids  = u.idsToString("#dg");
            u.confirm('是否确认删除?', () => $.get(u.url + "deleteshop", {"ids": ids,"valid":'否'}, res => {
                u.tool1('删除成功');
            }))

        }
    }
    //恢复客户
    u.hfshop = function(){
        if (u.is_select_one("请勾选数据后再操作")) {
            // let data = $("#dg").datagrid('getSelections');
            // let ids = [];
            // for(let i = 0;i<data.length;i++){
            //     ids.push(data[i]['id']);
            // }
            let ids  = u.idsToString("#dg");
            u.confirm('是否确认恢复?', () => $.get(u.url + "deleteshop", {"ids": ids,"valid":'是'}, res => {
                u.tool1('恢复成功');
            }))
        }
    }

    //保存数据
    u.saveshop = function () {
        let formdata = $("#form2").serializeObject(), tips = '';
        let data = $("#dg").datagrid('getSelected');
        formdata.id = data.id;
        tips = formdata.id != "" ? '更新信息成功' : '更新信息成功';
        u.confirm('确认保存数据吗?', () => $.get(u.url + "add_update_shop", formdata, res => {
            $("#dg2").datagrid('reload');
            u.tool1(tips)
        }));
    }
    //新增客户
    u.addkh = function () {
        let formdata = $("#form3").serializeObject(), tips = '';
        tips = formdata.id != "" ? '新增客户成功' : '新增客户成功';
        u.confirm('确认保存数据吗?', () => $.get(u.url + "addkh", formdata, res => u.tool1(tips)));
    }
    //领取客户
    u.khlq = function(){
        if (u.is_select_one("请勾选数据后再操作")) {
            // let data = $("#dg").datagrid('getSelections'),tips = '';
            // let ids = [];
            // for(let i = 0;i<data.length;i++){
            //     ids.push(data[i]['id']);
            // }
            let ids  = u.idsToString("#dg");
            let tips = "领取客户成功";
            u.confirm('确认领取客户吗?', () => $.get(u.url + "khlq", {"ids":ids}, res => u.tool1(tips)));
        }
    }
    //放弃客户，回到公海中去
    u.fqkh = function(){
        if (u.is_select_one("请勾选数据后再操作")) {
            // let data = $("#dg").datagrid('getSelections'),tips = '';
            // let ids = [];
            // for(let i = 0;i<data.length;i++){
            //     ids.push(data[i]['id']);
            // }
            let ids  = u.idsToString("#dg");
            let tips = "放弃客户成功";
            //tips = data.id != "" ? '放弃客户成功' : '放弃客户成功';
            u.confirm('确认放弃客户吗?', () => $.get(u.url + "fqkh", {"ids":ids}, res => u.tool1(tips)));
        }
    }

    //把ids转换为string输出
    u.idsToString = function(obj) {
        let data = $(obj).datagrid('getSelections'),ids = [];
        for(let i = 0;i<data.length;i++){
            ids.push(data[i]['id']);
        }
        return ids.toString()
    }

    //物流信息录入
    u.wlxxlr = function () {
        if (u.is_select_one("请勾选数据后再操作")) {
            let data = $("#dg").datagrid('getSelected');
            $('#w1').window({
                title: '物流信息录入', width: 600, height: 150, modal: true, onClose: function () {
                    u.reloadTable();
                    $("#form2").form("clear");
                }
            });
            $('#w1').window('open');
        }
    }
    //录入更新物流单号
    u.savewldh = function () {
        let formdata = $("#form2").serializeObject();
        let data = $("#dg").datagrid('getSelected');
        formdata["id"] = data.id;
        u.confirm('确认保存数据吗?', () => $.get(u.url + "savewldh", formdata, res => u.tool1("更新物流单号成功")));
    }
    //兑换记录作废
    u.dhjlzf = function () {
        if (u.is_select_one("请勾选数据后再操作")) {
            let data = $("#dg").datagrid('getSelected');
            u.confirm('是否确认作废兑换记录?', () => $.get(u.url + "dhjlzf", data, res => u.tool1("作废兑换记录成功")));
        }
    }
    u.edituserinfo = function () {
        $('#dialog').window({title: '用户信息编辑', width: 600, height: 500, modal: true, onClose: () => u.reloadTable()});
        let data = $("#dg").datagrid('getSelected');
        $.get($api.url + 'getuserinfo', {"id": data.id}, res => {
            let [obj] = res;
            $('#updateform').form('load', obj);
            $('#dialog').window('open');
        });
    }
    u.updateuserinfo = function () {
        let obj = $("#updateform").serializeObject();
        let data = $("#dg").datagrid('getSelected');
        obj["id"] = data.id;
        $.get($api.url + "updateuserinfo", obj, res => u.infoDialog("更新成功"));
    }
    u.regbtn = function () {
        $.post(u.url + "appreg", $("#regform").serializeObject(), res => {
            let [tip] = res.error;
            if (res.flag == "success") {
                $("#loginbox-show").show();
                $("#regbox-show").hide();
                $('.login3-title li').removeClass();
                $("#loginbox").addClass("active");
            }
            layer.msg(tip);
        }, 'json');
    }
    /**
     * 网站登陆方法
     */
    u.applogin = function () {
        $.post(u.url+'applogin',$("#loginform").serializeObject(),res=>{
            let [tip] = res.error;
            layer.msg(tip);
            if(tip=='登录成功'){
                window.location.href='view_index';
            }
        })
    },
    u.searchList = function(){
        let wd = $('.swd').val();
        window.open(`view_search?wd=${wd}`);
    },
    /**
     * 登陆账号智能检测
     */
    u.verify_login = function () {

    },
    u.info_dialog = function (str) {
        $.messager.alert('提示消息', str, 'info');
    }
    u.tool1 = function (str) {
        u.infoDialog(str);
        u.reloadTable();
        u.winclose("#w1");
    }
    //关闭窗体
    u.winclose = obj => {
        $(obj).window("close")
    };
    u.reloadTable = () => $("#dg").datagrid('reload');
    //确认是否勾选，
    u.is_select_one = msg1 => {
        let data = $("#dg").datagrid('getSelected');
        if (!data) {
            u.infoDialog(msg1);
            return false;
        }
        return true;
    }
    u.infoDialog = str => {
        $.messager.alert('提示消息', str, 'info');
        u.reloadTable();
    }
    u.confirm = function (tips, callback) {
        $.messager.confirm('提示信息', tips, function (r) {
            if (r) callback();
        });
    }
        /**
         * 点击下载模型
          */
    u.downloadfiles = (gid)=>{
        // let obj = {down_type, gid} = $("#gform").serializeObject();
        $.get(u.url+'downloadfile',{gid},res=>{
            //console.log(res);
            if(res.flag=='success'){
                layer.msg('可以下载');
                var a = document.createElement('a');
                a.href = res.url; //图片地址
                a.download = "模型.zip"; //图片名及格式
                a.style.display='none';
                a.className='downbtn';
                document.body.appendChild(a);
                a.click();
                $('.downbtn').remove();
                //window.location.href = "";
                //window.open(res.url);
            }else if(res.flag=='fail'){
                layer.msg('非法下载');
            }
        },'json');
    }
    /**
     * 扩展jq对象
     * 调用方式:$("#input1").alertWhileClick()
     * @return 返回扩展之后的jq对象
     *
     */
    $.fn.extend({
        serializeObject: function () {
            let o = {}, a = this.serializeArray();
            $.each(a, function () {
                if (o[this.name] !== undefined) {
                    if (!o[this.name].push) {
                        o[this.name] = [o[this.name]];
                    }
                    o[this.name].push(this.value || '');
                } else {
                    o[this.name] = this.value || '';
                }
            });
            return o;
        },
    });
    window.$api = u;
})(window);
/**
 * 扩展jq对象
 * 调用方式:$.alertWhileClick()
 * @return 返回扩展之后的jq对象
 *
 */
$.extend({
    formatDate: function (date) {
        let y = date.getFullYear(), m = date.getMonth() + 1, d = date.getDate();
        return y + '-' + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d);
    },
    myParse: function (s) {
        if (!s) return new Date();
        let ss = (s.split('-')), y = parseInt(ss[0], 10), m = parseInt(ss[1], 10), d = parseInt(ss[2], 10);
        return (!isNaN(y) && !isNaN(m) && !isNaN(d)) ? new Date(y, m - 1, d) : new Date();
    },
    carousel: function () {
        let swiper = new Swiper('.swiper-container', {
            pagination: '.swiper-pagination',
            paginationClickable: true,
            paginationBulletRender: function (swiper, index, className) {
                return '<span class="' + className + '">' + (index + 1) + '</span>';
            }
        });
    }
})
